package com.jhf.youke.db.config;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Properties;


/**
 * 本拦截器主要功能为自动增加带单位权限查询，只查本单位以及下级单位数据
 *
 * @author RHJ
 */
@Slf4j
public class MybatisCompanyPermissionIntercept implements InnerInterceptor {
    private static final String COMPANY_IDS = "companyIds";

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {

        Object parameterObject = boundSql.getParameterObject();
        if (parameterObject != null) {
            Map<String, Object> objectMap = BeanUtil.beanToMap(parameterObject);
            if (objectMap.containsKey(COMPANY_IDS)) {
                String companyIds = (String) objectMap.get(COMPANY_IDS);
                if (StringUtils.isNoneBlank(companyIds)) {
                    try {

                        String sql = boundSql.getSql();
                        log.info("原始 sql {} }", boundSql.getSql());
                        String before = StringUtils.substringBefore(sql, "WHERE");

                        String after = StringUtils.substringAfter(sql, "WHERE");

                        String limitBefore = StringUtils.substringBefore(after, "LIMIT");

                        String limit = StringUtils.substringAfter(after, "LIMIT");

                        String mSql = before + "WHERE" + limitBefore + " AND a.company_id in (" + companyIds + ")";
                        if (!StringUtils.isBlank(limit)) {
                            mSql += " LIMIT " + limit;
                        }
                        log.info("修改后 sql {} }", mSql);
                        // 直接修改sql
                        Field field = boundSql.getClass().getDeclaredField("sql");
                        field.setAccessible(true);
                        field.set(boundSql, mSql);

                    } catch (Exception e) {
                        log.info(e.getMessage());
                    }

                }
            }
        }

    }


    @Override
    public void setProperties(Properties properties) {
        log.info("properties {}", properties.toString());
    }


}


